﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Jb.Common.Extensions;
using Jb.Domain;
using Jb.Web.ViewModels;
using Jb.Web.Utility;
using AutoMapper;
using System.Web.Script.Serialization;
using System.Text;

namespace Jb.Web.Controllers
{
    public class AjaxController : BaseController
    {
        private JbEntities _Context;
        
		#region Constructors
		public AjaxController()
		{
            _Context = new JbEntities();
		}

		public AjaxController(UserViewModel currentUser)
			: base(currentUser)
        {
            _Context = new JbEntities();
        }
		#endregion Constructors

		#region Action Methods
        /// <summary>
        /// Gets a JSON Collection of districts/states by Country
        /// </summary>
        /// <param name="countryID"></param>
        /// <returns></returns>
        public String GetStatesByCountry(int countryID)
        {
            var query = from P in _Context.States
                        where P.CountryID == countryID
                        orderby P.Name
                        select new
                        {
                            ID = P.ID,
                            Name = P.Name
                        };
            if (query == null || query.Count() == 0)
                return null;
            else
                return query.ToList().ToJSON();
        }

        /// <summary>
        /// Gets a JSON collection of cities by state
        /// </summary>
        /// <param name="stateID"></param>
        /// <returns></returns>
        public String GetCitiesByState(int stateID)
        {
            var query = from P in _Context.Cities
                        where P.StateID == stateID
                        orderby P.Name
                        select new
                        {
                            ID = P.ID,
                            Name = P.Name
                        };
            if (query == null || query.Count() == 0)
                return null;
            else
                return query.ToList().ToJSON();
        }

        /// <summary>
        /// Gets Category Bradcrumb
        /// </summary>
        /// <param name="categoryID"></param>
        /// <returns></returns>
        /// [HttpPost]
        public PartialViewResult GetCategoryBreadCrumb(int categoryID)
        {
            return PartialView("_CategoryBreadCrumb", categoryID);
        }

        /// <summary>
        /// Gets JSON collection of Job Skiil by category ID
        /// </summary>
        /// <param name="categoryID"></param>
        /// <returns></returns>
        public String GetSkills(int categoryID)
        {
            var query = _Context.Skills.Where(P => P.CategoryID == categoryID).ToList();
            List<SkillViewModel> skills = AutoMapper.Mapper.Map<List<SkillViewModel>>(query);
            return skills.ToJSON();
        }

        /// <summary>
        /// Deletes a temporary image by the given path. This is typically /Tmp
        /// </summary>
        /// <param name="imagePath"></param>
        /// <returns></returns>
        [HttpPost]
        public bool DeleteTempImage(String imagePath)
        {
            String fileName = System.IO.Path.GetFileName(imagePath);            
            fileName = System.IO.Path.Combine(Server.MapPath(AppConstants.Directories.TEMP), fileName);
            if (System.IO.File.Exists(fileName))
            {
                System.IO.File.Delete(fileName);
                return true;
            }
            return false;
        }

        /// <summary>
        /// Checks Status of a ongoing ReIndex Operation
        /// </summary>
        /// <param name="jobID"></param>
        /// <returns></returns>
        [HttpGet]
        public String CheckStatus(int jobID)
        {
            var process = (from P in _Context.ProcessStatuses
                           where P.ID == jobID
                           select new
                           {
                               ID = P.ID,
                               Total = P.Total,
                               Completed = P.Completed,
                               Status = P.Status,
                               Error = P.Message
                           }).FirstOrDefault();
            if (process != null)
                return process.ToJSON();

            return String.Empty;
        }

        /// <summary>
        /// Adds a Resume to the Company Favorite Resume List
        /// </summary>
        /// <param name="resumeID"></param>
        /// <param name="jobID"></param>
        /// <returns>Returns 1 f added successfully otherwise -1 if permission denied</returns>
        [HttpPost]
        public int AddToFavoriteResume(int resumeID, int? jobID = null)
        {
            if (UserInfo.IsCompanyUser)
            {
                FavoriteResume favorite = _Context.FavoriteResumes.FirstOrDefault(P => P.ResumeID == resumeID && P.CompanyID == LoggedInUser.Contact.CompanyID);
                if (favorite == null)
                {
                    favorite = new FavoriteResume();
                    favorite.CompanyID = LoggedInUser.Contact.CompanyID;
                    favorite.ResumeID = resumeID;
                    favorite.JobID = jobID;
                    favorite.ModifiedOn = DateTime.Now;
                    favorite.CreatedOn = DateTime.Now;

                    _Context.AddToFavoriteResumes(favorite);
                    _Context.SaveChanges();
                }
                return 1;
            }
            return -1;
        }

        /// <summary>
        /// Adds a Job to the Favorite Job List of a Job Seeker
        /// </summary>
        /// <param name="resumeID"></param>
        /// <param name="jobID"></param>
        /// <returns>Returns 1 f added successfully otherwise -1 if permission denied</returns>
        [HttpPost]
        public int AddToFavoriteJob(int jobID, String url = null)
        {
            if (UserInfo.IsJobSeeker)
            {
                FavoriteJob favorite = _Context.FavoriteJobs.FirstOrDefault(P => P.JobID == jobID && P.UserID == LoggedInUser.ID);
                if (favorite == null)
                {
                    favorite = new FavoriteJob();
                    favorite.UserID = LoggedInUser.ID;
                    favorite.JobID = jobID;
                    favorite.ModifiedOn = DateTime.Now;
                    favorite.CreatedOn = DateTime.Now;

                    _Context.AddToFavoriteJobs(favorite);
                    _Context.SaveChanges();
                    SessionCache.RefreshUserInfo();
                }
                return 1;
            }
            else
                SessionCache.RedirectUrl = url.Replace(WebUtil.GetDomainAddress(), String.Empty);
            return -1;
        }        

        /// <summary>
        /// Sends a job to a friend.
        /// </summary>
        /// <param name="jobID"></param>
        /// <param name="userEmail"></param>
        /// <param name="friendEmail"></param>
        /// <returns>
        /// Returns different status based on situations. 
        /// Status > 0 -> Successfully Sent
        /// -1 -> Invalid Request
        /// -2 -> The Requested Job was not found, probably a hacking attempt
        /// -3 -> Unable to send the email, probably a SMTP server issue.
        /// </returns>
        [HttpPost]
        public int SendJobToFriend(int jobID, String userEmail, String friendEmail)
        {
            if (jobID <= 0 || userEmail.IsNullOrEmpty() || friendEmail.IsNullOrEmpty())
                return -1;

            Job job = _Context.Jobs.FirstOrDefault(P => P.ID == jobID);
            if (job == null)
                return -2;
            else
            {
                StringBuilder template = new StringBuilder(WebUtil.ReadEmailTemplate(AppConstants.EmailTemplate.COMMON));
                StringBuilder message = new StringBuilder(10);
                message.Append("Hi,<br />");
                message.AppendFormat("Your friend send you a job from {0}. Please check below:<br/><br/>", ConfigReader.SiteName);
                message.AppendFormat("<b>Job Title:</b><br/> {0}<br/><br/>", WebUtil.FormatData(job.Title));
                message.AppendFormat("<b>Job Description:</b><br/> {0}<br/><br/>", WebUtil.FormatData(job.Description));
                message.AppendFormat("For more details visit this <a href='{0}'>job details</a> page.", Url.JobDetailsUrl(jobID, job.Url, null, true));
                template.Replace(AppConstants.ETConstants.MESSAGE, message.ToString());
                template.Replace(AppConstants.ETConstants.DOMAIN, WebUtil.GetDomainAddress());
                String subject = String.Format("Received a job from {0}", ConfigReader.SiteName);
                if (WebUtil.SendMail(userEmail, friendEmail, ConfigReader.AdminEmail, String.Empty, subject, template.ToString()))
                    return 1;
                
                return -3;
            }
        }

        /// <summary>
        /// Get the Cover Letter Application for a given Cover Letter ID 
        /// Of the currently logged in user.
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public String GetApplication(int id = 0)
        {
            if (UserInfo.IsJobSeeker)
            {
                CoverLetter entity = _Context.CoverLetters.FirstOrDefault(P => P.ID == id && P.JobSeekerID == LoggedInUser.JobSeekerID);
                if (entity != null)
                    return entity.Application;
            }
            return String.Empty;
        }

        /// <summary>
        /// Gets Resume Snapshot by resume id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public String GetResumeSnapShot(int id = 0)
        {
            if (UserInfo.IsJobSeeker)
            {
                Resume resume = _Context.Resumes.FirstOrDefault(P => P.ID == id);
                if (resume != null && resume.JobSeekerID == LoggedInUser.JobSeekerID)
                    return resume.SnapShot.IsNullOrEmpty() ? "N/A" : WebUtil.FormatData(resume.SnapShot);
            }
            return "N/A";
        }
        /// <summary>
        /// Saves a Cover letter for a Job Seeker        
        /// </summary>
        /// <param name="title"></param>
        /// <param name="application"></param>
        /// <returns>
        /// Returns following Statuses
        /// -1 -> User exceeded coverletter saving quota
        /// -2 -> User is not authorized to save a coverletter
        /// +1 -> Cover Letter Saved successfully.
        /// </returns>
        [HttpPost]
        [ValidateInput(false)]
        public int SaveCoverLetter(String title, String application)
        {
            if (UserInfo.IsJobSeeker)
            {
                if (_Context.CoverLetters.Count(P => P.JobSeekerID == LoggedInUser.JobSeekerID) < SiteConfigReader.MaxCoverLetter)
                {
                    CoverLetter coverLetter = new CoverLetter();
                    coverLetter.Title = title;
                    coverLetter.Application = application;
                    coverLetter.JobSeekerID = LoggedInUser.JobSeekerID;
                    coverLetter.IsDefault = false;
                    _Context.AddToCoverLetters(coverLetter);

                    _Context.SaveChanges();                        
                    return coverLetter.ID;
                }
                else
                    return -1;
            }
            return -2;
        }
		#endregion Action Methods
		
		#region Helper Methods

        #endregion			
    }
}
